#include <boost/asio.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <iostream>
#include <thread>
#include <sys/eventfd.h>
#include <unistd.h>
#include "debug_utils.h"

using namespace boost::asio;

class EventfdExample {
private:
    io_context io_;
    posix::stream_descriptor eventfd_descriptor_;
    int eventfd_handle_;
    
public:
    EventfdExample() : eventfd_descriptor_(io_) {
        eventfd_handle_ = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
        if (eventfd_handle_ == -1) {
            throw std::runtime_error("Failed to create eventfd");
        }
        
        eventfd_descriptor_.assign(eventfd_handle_);
        
        DEMO_INFO("EventFD 创建成功，文件描述符: {}", eventfd_handle_);
    }
    
    ~EventfdExample() {
        if (eventfd_handle_ != -1) {
            close(eventfd_handle_);
        }
    }
    
    void start_async_wait() {
        DEMO_INFO("开始异步等待 eventfd 事件...");
        
        async_read_eventfd();
    }
    
    void trigger_event(uint64_t value = 1) {
        DEMO_INFO("触发事件，写入值: {}", value);
        
        // 向eventfd写入一个64位值
        ssize_t result = write(eventfd_handle_, &value, sizeof(value));
        if (result != sizeof(value)) {
            DEMO_ERROR("写入 eventfd 失败");
        }
    }
    
    void run() {
        io_.run();
    }
    
    void stop() {
        io_.stop();
    }
    
private:
    void async_read_eventfd() {
        // 创建缓冲区来读取eventfd的值
        auto buffer = std::make_shared<uint64_t>();
        
        // 异步读取eventfd
        eventfd_descriptor_.async_read_some(
            boost::asio::buffer(buffer.get(), sizeof(*buffer)),
            [this, buffer](const boost::system::error_code& ec, std::size_t bytes_read) {
                if (!ec && bytes_read == sizeof(*buffer)) {
                    DEMO_INFO("接收到 eventfd 事件，值: {}", *buffer);
                    
                    // 继续等待下一个事件
                    async_read_eventfd();
                } else if (ec == boost::asio::error::operation_aborted) {
                    DEMO_INFO("EventFD 读取操作被取消");
                } else {
                    DEMO_ERROR("EventFD 读取错误: {}", ec.message());
                    
                    // 重试读取
                    std::this_thread::sleep_for(std::chrono::milliseconds(100));
                    async_read_eventfd();
                }
            }
        );
    }
};

// 演示线程间通信
void demonstrate_thread_communication() {
    DEMO_INFO("=== 线程间通信演示 ===");
    
    EventfdExample example;
    
    // 启动异步等待
    example.start_async_wait();
    
    // 在另一个线程中运行IO服务
    std::thread io_thread([&example]() {
        example.run();
    });
    
    // 在主线程中定期触发事件
    for (int i = 1; i <= 5; ++i) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        example.trigger_event(i);
    }
    
    // 停止IO服务
    std::this_thread::sleep_for(std::chrono::seconds(1));
    example.stop();
    
    if (io_thread.joinable()) {
        io_thread.join();
    }
    
    DEMO_INFO("线程间通信演示完成");
}

int main() {
    try {
        DEMO_INFO("Boost.Asio EventFD 使用示例");
        DEMO_INFO("==============================");
        
        demonstrate_thread_communication();
        
    } catch (const std::exception& e) {
        DEMO_ERROR("错误: {}", e.what());
        return 1;
    }
    
    return 0;
}
